const sqlite3 = require("sqlite3")
const { tableName } = require('../config/config')

let isLoadDb = false
const db = new sqlite3.Database("./my_data.db", (err) => {
    if (err) {
        throw err
    } else {
        console.log(db, '数据库连接成功')
        isLoadDb = true
        createTable()
    }
})

// 创建表
const createTable = () => {
    if (!isLoadDb) {
        console.log('数据库未加载')
        return
    }
    db.run(`CREATE TABLE "${tableName}" (
        "id"	INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
        "timestamp"	TEXT,
        "data"	INTEGER
    );`, (err) => {
        if (err) {
            if (err.message.split(': ')[1] === `table "${tableName}" already exists`) {
                console.log('已经存在数据表')
            } else {
                console.log('未知错误 createTable', err)
            }
        } else {
            console.log("数据表创建成功")
        }
    })
}

// 插入数据
const insertData = (data) => {
    if (!isLoadDb) {
        console.log('数据库未加载')
        return
    }
    return new Promise((resolve, reject) => {
        db.run(`insert into ${tableName} values (NULL, ${Date.now()}, "${data}")`, (err) => {
            if (err) {
                reject()
                throw err
            } else {
                console.log("数据插入成功")
                resolve()
            }
        })
    })

}

module.exports = {
    createTable,
    insertData
}